$(function () {
    $('.select2').select2();
    var defaultColunms = BaseTable.initColumn();
    var table = new BSTable(BaseTable.id, "/wx/user/back/list", defaultColunms);
    table.setQueryParams({flag: 1});
    table.setPaginationType("server");
    BaseTable.table = table.init();
    initFileInput('input-id');
});

/**
 * 表格类容初始化
 */
var BaseTable = {
    id: "table",	//表格id
    seItem: null,		//选中的条目
    table: null,
};

/**
 * 初始化表格的列
 */
BaseTable.initColumn = function () {
    return [
        {field: 'selectItem',align: 'center', valign: 'middle',checkbox : true},
        {field: 'id',title : '序号',align: 'center', valign: 'middle',formatter : function(value, row, index) {return index+1;}},
        {title: '略缩图', field: 'url', align: 'center', valign: 'middle', formatter: function(value, row, index){
            var html = '<a target="_blank" href="'+value+'"><image src="'+value+'" style="width: 50px;height: 50px"/></a>'
            return html;
        }},
        {title: '状态', field: 'enabled', align: 'center', valign: 'middle', formatter: function(value, row, index){
            return '已删除';
        }},
        {title: '创建时间', field: 'createTime', align: 'center', valign: 'middle', sortable: true},
        {title: '操作', field: 'status', align: 'center', valign: 'middle', formatter: function(value, row, index){
            var html = '<div style="display: flex;justify-content: center">'
            html += '<a style="margin: 0 10px" class="btn btn-danger " href="#" onclick="remove('+row.id+')"><i class="fa fa-trash-o">删除</i></a>';
            html += '<a style="margin: 0 10px" class="btn btn-primary " href="#" onclick="update('+row.id+')">恢复</a>';
            html += '</div>'
            return html;
        }}
    ];
};

/**
 * 检查是否选中
 */
BaseTable.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        alert("请先选中表格中的某一记录！");
        return false;
    } else {
        BaseTable.seItem = selected[0];
        return true;
    }
};


/**
 * 查询表格列表
 */
BaseTable.search = function () {
    var queryData = {};
    queryData['flag'] = 1;
    BaseTable.table.refresh({query: queryData});
};

function update(id) {
    var params = {
        id:id,
        status:1
    }
    ajaxSubmit("/wx/user/back/update",JSON.stringify(params),function (r) {
        if (r.code === 0) {
            showSuccessMsg("操作成功！",function () {
                vm.reload()
            });
        } else {
            alert(r.msg);
        }
    })
}
function remove(id) {
    var ids = new Array();
    ids.push(id);
    showWarningMsg('确定要删除当前选中的信息吗',function () {
        ajaxSubmit("/wx/user/back/delete",JSON.stringify(ids), function (r) {
            if (r.code === 0) {
                showSuccessMsg("操作成功！",function () {
                    reloadPage();
                });
            } else {
                alert(r.msg);
            }
        })
    })
}

function clearInput(obj) {
    $(obj).prev().val('');
}


var vm = new Vue({
    el:'#app',
    data:{
        showList: true,
        data:{}
    },
    methods: {
        add: function(){
            vm.data = {status:1};
            vm.showList = false;
        },
        del: function () {
            //获取选中的列
            var ids = getSelections('table', 'id');
            if (ids.length == 0) {
                alert('请选择需要删除的数据！');
                return;
            }
            console.info(ids);
            showWarningMsg('确定要删除选中的记录？',function () {
                ajaxSubmit('/wx/user/back/delete',JSON.stringify(ids),function (r) {
                    if(r.code == 0){
                        showSuccessMsg('操作成功!');
                        vm.reload();
                    }else{
                        alert(r.msg);
                    }
                })
            })
        },
        upload:function () {
            var isUpload = $("#input-id").fileinput("validate");
            if (isUpload) {
                $("#input-id").fileinput("upload");
            }
        },
        reload: function () {
            BaseTable.search();
            vm.showList = true;
        }
    }
});

function initFileInput(ctrlName) {
    var control = $('#' + ctrlName);
    control.fileinput({
        language: 'zh', //设置语言
        uploadUrl: "/wx/user/back" + "/upload", //上传的地址
        allowedPreviewTypes: ['image'],
        allowedFileExtensions: ['jpg', 'png', 'jpeg'],//接收的文件后缀
        maxFilesNum: 10,//上传最大的文件数量
        uploadAsync: false, //默认异步上传
        fileActionSettings: {
            showZoom: false,
            showDelete: true,
            showUpload: false
        },
        showRemove: true,
        showUpload: false, //是否显示上传按钮,跟随文本框的那个
        browseClass: "btn btn-primary", //按钮样式
        dropZoneEnabled: true,//是否显示拖拽区域
        maxFileSize: 20000,//单位为kb，如果为0表示不限制文件大小
        minFileCount : 1,
        maxFileCount:20, //表示允许同时上传的最大文件个数
        enctype: 'multipart/form-data',
        validateInitialCount: true,
        previewFileIcon: '<i class="fa fa-file-photo-o text-primary"></i>',
        previewFileIconSettings: {
            'jpg': '<i class="fa fa-file-photo-o text-danger"></i>',
            'gif': '<i class="fa fa-file-photo-o text-warning"></i>',
            'png': '<i class="fa fa-file-photo-o text-primary"></i>'
        },
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
    }).on("filebatchuploadsuccess", function (event, data, previewId, index) {//
        var response = data.response;
        if (response.code==0) {
            showSuccessMsg('上传成功！',function () {
                vm.reload();
            })
        }
    }).on("filebatchselected", function (event, files) {
        // trigger upload method immediately after files are selected
    }).on('filebatchuploaderror', function (event, data, msg) {  //
        console.log('文件上传失败！' + data.response);
    }).on('filepreupload', function (event, data, previewId, index) {     //上传中
        var form = data.form, files = data.files, extra = data.extra,
            response = data.response, reader = data.reader;
        console.log('文件正在上传');
    }).on("filepredelete", function (jqXHR, fileName) {
        var abort = false;
        if (showWarningMsg("确认删除该文件?")) {
            abort = true;
        }
        return abort;
    });
}
